<template>
	<!-- 附近的人 -->
	<Top-Page>
		<cu-custom bgColor="bg-gradual-white" :isBack="true">
			<template #backText></template>
			<template #content>附近的人</template>
			<!-- <template #right>
        <view class="cu-right">···</view>
      </template> -->
		</cu-custom>

		<!-- 筛选栏 -->
		<view class="filtrate-wrap">
			<view class="filtrate">
				<template v-for="item in selectedData">
					<template v-for="(itList, key) in item">
						<view class="filtrate__value" v-for="it in itList">
							<view>{{ it }}</view>
							<view class="close-css_icon filtrate--close" @click="delSelected(key, it)"></view>
						</view>
					</template>
				</template>
			</view>
			<view @click="show = !show">筛选</view>
		</view>

		<view class="list">
			<view class="list-item border-bottom-before" v-for="item in list" @click="toDetail(item.user_id)">
				<image class="list-item__left avatar" :src="item.avatar" mode="aspectFit" />
				<view class="list-item__right">
					<view class="list-item__right-top">
						<view class="name">
							{{ item.realname }}
						</view>

						<image class="sex" v-if="item.sex < 2" :src="`${sexImgPath}${item.sex}.png`" mode="aspectFit" />

						<view class="level" v-if="item.level?.icon">
							<image class="level-img" :src="`${item.level?.icon}`" mode="aspectFit" />
							{{ item.level?.name }}
						</view>
					</view>

					<view class="list-item__right-detail">
						<view class="detail-item" v-if="item.township">{{ item.township }}</view>
						<view class="detail-item" v-if="item.distance">{{ item.distance }}</view>
						<view class="detail-item" v-if="item.age">{{ item.age }}岁</view>
						<view class="detail-item" v-if="item.motto">{{ cutOut(item.motto, 20) }}</view>
					</view>
				</view>
			</view>

			<Empty v-if="finished && !list.length" noDatatext="暂无数据" textcolor="#999"></Empty>

			<view class="finished__text" v-if="finished && list.length">没有更多了</view>
		</view>

		<popups :closeOnClickOverlay="false" v-model:show="show" position="right">
			<view v-for="(item, itemIndex) in filtrateData" :key="itemIndex" class="filtrate-item">
				<view class="filtrate-item__title">{{ item.title }}</view>

				<view class="filtrate-item__list">
					<view
						v-for="(option, optionIndex) in item.options"
						:key="optionIndex"
						:class="['filtrate-item__list-li', { on: option.isSelected }]"
						@click="handleOptionClick(itemIndex, optionIndex)"
					>
						{{ option.text }}
					</view>
				</view>
			</view>

			<view class="btns-wrap">
				<view class="btn" @click="handleClose">取消</view>
				<view class="btn" @click="handleConfirm">确定</view>
			</view>
		</popups>
	</Top-Page>
</template>

<script lang="ts" setup>
import popups from "@/components/Popups/index.vue"
import api from "@/api/index.js"
import { onReachBottom } from "@dcloudio/uni-app"
import { ref, reactive, computed } from "vue"

interface FiltrateOption {
	text: string // 选项的显示文本
	isSelected: boolean // 选项是否被选中
}

interface FiltrateItem {
	title: string // 筛选项标题
	name: string // 名称
	options: FiltrateOption[] // 筛选项的选项列表
	isMultiple: boolean // 是否允许多选
}

const sexImgPath = "../../static/image/rests/sex"
const list = reactive([]) // 用户列表
const filtrateData: FiltrateItem[] = reactive([]) //筛选的条件
const show = ref(false)
const finished = ref(false)
let num = 0 //获取附近的人,上一次最后一条的num属性

//选中的内容
const selectedData = computed(() => {
	return filtrateData.map((item) => {
		return {
			[item.name]: item.options.filter((option) => option.isSelected).map((option) => option.text),
		}
	})
})

onReachBottom(() => {
	if (finished.value) return
	nearbyGet()
})

/*
 * 获取当前的地理位置
 */
const getLocation = () => {
	uni.showToast({
		title: "查找中...",
		icon: "loading",
		duration: 999999,
		mask: true,
	})
	// init();

	uni.getLocation({
		type: "gcj02",
		success: (res) => {
			init(res.longitude, res.latitude)
		},
		fail: () => {
			uni.hideToast()

			uni.showToast({
				title: "查找失败，请重新尝试",
				icon: "none",
			})
		},
	})
}

// 获取筛选过滤配置，初始定位信息
const init = (longitude: number, latitude: number) => {
	api.friendApi
		.nearbySet({
			lng: longitude || 104.280831,
			lat: latitude || 30.352266,
		})
		.then((res) => {
			const { data } = res

			filtrateData.length = 0
			list.length = 0

			if (Array.isArray(data.filter)) {
				data.filter.length && filtrateData.push(...data.filter)
			} else {
				uni.showToast({
					title: "filter内容错误，请联系管理员",
					icon: "none",
				})
			}

			nearbyGet()
		})
}

// 获取附近的人
const nearbyGet = () => {
	const params = { num: num }

	selectedData.value.forEach((item) => {
		Object.assign(params, item)
	})

	api.friendApi.nearbyGet(params).then((res) => {
		uni.hideToast()
		const { data } = res

		data.length < 12 && (finished.value = true)
		num = data[data.length - 1].num
		list.push(...data)
	})
}

//筛选
const handleOptionClick = (itemIndex: number, optionIndex: number) => {
	const item = filtrateData[itemIndex]
	const option = item.options[optionIndex]

	if (!item.isMultiple) {
		// 单选：如果当前选项已被选中，则取消选中；否则取消其他选项并选中当前选项
		if (option.isSelected) {
			option.isSelected = false
		} else {
			item.options.forEach((opt) => (opt.isSelected = false))
			option.isSelected = true
		}
	} else {
		// 多选：切换当前选项的选中状态
		option.isSelected = !option.isSelected
	}
}

//删除当前选择
const delSelected = (key: string | number, selectedOption: string) => {
	filtrateData.forEach((item) => {
		item.name === key &&
			item.options.forEach((option) => {
				if (option.text === selectedOption) {
					option.isSelected = false
				}
			})
	})

	handleConfirm()
}

//跳转toDetail
const toDetail = (id: number) => {
	uni.navigateTo({
		url: `/pages/contacts/detail?id=${id}&group_id=group_nearby`,
	})
}

// 搜索 -- 确定
const handleConfirm = () => {
	uni.showToast({
		title: "查找中...",
		icon: "loading",
		duration: 999999,
		mask: true,
	})

	list.length = 0
	num = 0
	show.value = false
	nearbyGet()
}

//搜索 -- 关闭
const handleClose = () => {
	show.value = !show.value

	filtrateData.forEach((item) => {
		item.options.forEach((option) => {
			option.isSelected = false
		})
	})
}

// 截取指定数量个字符
const cutOut = (str: string, len?: number = 20) => {
	return str.length >= len ? str.slice(0, len) + "..." : str
}

getLocation()
</script>

<style lang="scss" scoped>
@import url("./index.scss");
</style>
